﻿Imports Microsoft.ApplicationBlocks.Data
Imports System.ComponentModel

Public Class frmBaseTreeView

    Dim p As Point
    Private PermissionType As clsPublicConstant.PermissionType

#Region "Vars"
    Private sTable1NameTree As String
    Private sTable2NameTree As String
    Private sTablePrimaryKeyTree As String 'Tên trường khóa của bảng
    Private sKeyParentNameIDTree As String 'Tên trường khóa mẹ
    Private sDisplayFieldTree As String 'Trường hiển thị trên cây
    Private sRelationName As String 'Tên quan hệ giữa 2 bảng or giữa một bảng với chính nó
    Private sProcGetAllDictionaryListTree As String ' Tên Store lấy dữ liệu của cả bảng danh mục
    Private sProcDeleteDictionaryListByIDTree As String 'Tên Store xóa dữ liệu của bảng danh mục theo ID
    Private sFormDetailNameTree As String
    Private oRowTree As DataRow
    Public oTreeKey As Object
    Private bShowTreeIcon As Boolean = True
    Private drRow As DataRow
    Private strKeyReturn As String

#End Region

#Region "Property"
    <Description("The dictionary row that is adding or editing"), Category("KTXTree")> _
    Public Property Table1NameTree() As String
        Get
            Return sTable1NameTree
        End Get
        Set(ByVal Value As String)
            sTable1NameTree = Value
        End Set
    End Property

    <Description("The dictionary row that is adding or editing"), Category("KTXTree")> _
    Public Property Table2NameTree() As String
        Get
            Return sTable2NameTree
        End Get
        Set(ByVal Value As String)
            sTable2NameTree = Value
        End Set
    End Property

    <Description("The dictionary row that is adding or editing"), Category("KTXTree")> _
    Public Property TablePrimaryKeyTree() As String
        Get
            Return sTablePrimaryKeyTree
        End Get
        Set(ByVal Value As String)
            sTablePrimaryKeyTree = Value
        End Set
    End Property

    <Description("The dictionary row that is adding or editing"), Category("KTXTree")> _
    Public Property KeyParentNameIDTree() As String
        Get
            Return sKeyParentNameIDTree
        End Get
        Set(ByVal Value As String)
            sKeyParentNameIDTree = Value
        End Set
    End Property

    <Description("The dictionary row that is adding or editing"), Category("KTXTree")> _
        Public Property DisplayFieldTree() As String
        Get
            Return sDisplayFieldTree
        End Get
        Set(ByVal Value As String)
            sDisplayFieldTree = Value
        End Set
    End Property

    <Description("The dictionary row that is adding or editing"), Category("KTXTree")> _
    Public Property RelationName() As String
        Get
            Return sRelationName
        End Get
        Set(ByVal Value As String)
            sRelationName = Value
        End Set
    End Property

    <Description("The dictionary row that is adding or editing"), Category("KTXTree")> _
    Public Property ProcGetAllDictionaryListTree() As String
        Get
            Return sProcGetAllDictionaryListTree
        End Get
        Set(ByVal Value As String)
            sProcGetAllDictionaryListTree = Value
        End Set
    End Property

    <Description("The dictionary row that is adding or editing"), Category("KTXTree")> _
    Public Property ProcDeleteDictionaryListByIDTree() As String
        Get
            Return sProcDeleteDictionaryListByIDTree
        End Get
        Set(ByVal Value As String)
            sProcDeleteDictionaryListByIDTree = Value
        End Set
    End Property

    <Description("The dictionary row tPat is adding or editing"), Category("KTXTree")> _
    Public Property FormDetailNameTree() As String
        Get
            Return sFormDetailNameTree
        End Get
        Set(ByVal Value As String)
            sFormDetailNameTree = Value
        End Set
    End Property

    <Description("The dictionary row that is adding or editing"), Category("KTXTree")> _
    Public Property RowTree() As DataRow
        Get
            Return oRowTree
        End Get
        Set(ByVal Value As DataRow)
            oRowTree = Value
        End Set
    End Property

    <Description("The dictionary row that is adding or editing"), Category("KTXTree")> _
        Public Property ShowTreeIcon() As Boolean
        Get
            Return bShowTreeIcon
        End Get
        Set(ByVal Value As Boolean)
            bShowTreeIcon = Value
        End Set
    End Property
#End Region



#Region "Overridable"

    Protected Overridable Function LoadDataTree()
        ' Load dữ liệu lên Tree
        Try
            clsDictionary.GetDictionary(goSession.Connection, sProcGetAllDictionaryListTree, sTable1NameTree, gdsDictionary)
            Dim ds As New DataSet
            ds = clsDictionary.GetDictionary(goSession.Connection, sProcGetAllDictionaryListTree, sTable1NameTree)
            ds.Relations.Add(RelationName, ds.Tables(sTable1NameTree).Columns(sTablePrimaryKeyTree), ds.Tables(sTable2NameTree).Columns(sKeyParentNameIDTree), False)
            ds.Relations(RelationName).Nested = True
            treeList.DataSource = ds.Tables(sTable1NameTree)
            'Added key for tree
            Dim node As Infragistics.Win.UltraWinTree.UltraTreeNode
            node = treeList.TopNode
            While Not node Is Nothing
                node.DataKey = node.Cells(sTablePrimaryKeyTree).Value
                node.Key = node.DataKey.ToString
                node = node.NextVisibleNode
            End While
            Return True
        Catch ex As Exception
            MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Return False
        End Try
    End Function


    Public Overridable Sub DeleteTree()
        Try
            If Not treeList.ActiveNode Is Nothing Then
                'kiem tra neu co con ben fai roi thi ko duoc xoa
                'kiem tra xem nut dang xet co phai la cha cua 1 nut nao do ko, neu fai thi ko xoa
                'Dim dsCheck As New DataSet
                'SqlHelper.FillDataset(gConnection, CommandType.StoredProcedure, "CheckExistChild", dsCheck, New String() {"abc"})
                Dim eResult As MsgBoxResult = MsgBox(ReadResource("DeleteQuestion"), MsgBoxStyle.Exclamation + MsgBoxStyle.YesNo)
                Dim obj As Object
                obj = treeList.ActiveNode.Cells(sTablePrimaryKeyTree).Value
                If eResult = MsgBoxResult.Yes Then
                    If clsDictionary.DeleteDictionary(goSession.Connection, sProcDeleteDictionaryListByIDTree, treeList.ActiveNode.Cells(sTablePrimaryKeyTree).Value) Then
                        If Not gdsDictionary.Tables(sTable1NameTree).Rows.Find(obj) Is Nothing Then
                            gdsDictionary.Tables(sTable1NameTree).Rows.Remove(gdsDictionary.Tables(sTable2NameTree).Rows.Find(obj))
                        End If
                        LoadDataTree()
                    End If
                End If
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub


#End Region

#Region "Event"
    Private Sub treeList_InitializeDataNode(ByVal sender As Object, ByVal e As Infragistics.Win.UltraWinTree.InitializeDataNodeEventArgs) Handles treeList.InitializeDataNode
        ' This event€u102 ?ires every time a node is added to the tree from 
        ' a data source. 

        ' Make sure that only the highest-level employees show up at
        ' the root level of the tree.
        If e.Node.Parent Is Nothing AndAlso _
            Not e.Node.Cells(sKeyParentNameIDTree).Value Is DBNull.Value Then
            e.Node.Visible = False
            Return
        End If

        ' Put a space before each parent node and color the parent
        ' nodes so the the tree is a little easier to read. 
        If e.Node.Nodes.Count > 0 Then
            ' No point in putting a space before the root node.
            If Not e.Node.Parent Is Nothing Then
                e.Node.Override.NodeSpacingBefore = 5
            End If

            'e.Node.Override.NodeAppearance.BackColor = Color.Yellow
            e.Node.Override.NodeAppearance.FontData.Bold = Infragistics.Win.DefaultableBoolean.True
        End If

        ' If Me is the root node (CEO) then expand it. 
        If e.Node.Parent Is Nothing Then
            e.Node.Expanded = True
            e.Node.Override.NodeAppearance.FontData.Bold = Infragistics.Win.DefaultableBoolean.True
        End If
        If Not e.Node.HasNodes Then
            e.Node.Expanded = True
        End If
        e.Node.ExpandAll()
        If bShowTreeIcon Then
            If e.Node.LeftImages.Count = 0 Then
                If e.Node.Level < 4 Then
                    e.Node.LeftImages.Add(imgTreeNode.Images(e.Node.Level))
                End If
            End If
        End If

    End Sub

    Private Sub treeList_ColumnSetGenerated(ByVal sender As Object, ByVal e As Infragistics.Win.UltraWinTree.ColumnSetGeneratedEventArgs) Handles treeList.ColumnSetGenerated
        e.ColumnSet.NodeTextColumn = e.ColumnSet.Columns(sDisplayFieldTree)
    End Sub

    Private Sub treeList_AfterSelect(ByVal sender As Object, ByVal e As Infragistics.Win.UltraWinTree.SelectEventArgs) Handles treeList.AfterSelect
        If Not treeList.SelectedNodes Is Nothing Then
            oTreeKey = treeList.ActiveNode.Key
            FilterObject()
            'GetRowCount()
        End If
    End Sub


    Private Sub tbrMain_ToolClick(ByVal sender As System.Object, ByVal e As Infragistics.Win.UltraWinToolbars.ToolClickEventArgs) Handles tbrMain.ToolClick
        Try
            Dim sSecureAccessKey As String = clsCommonFunction.GetFormParameter(Me.Tag, 1)
            Select Case e.Tool.Key
                Case "mnuNewTree"    ' ButtonTool
                    'Check permision
                    If sSecureAccessKey <> "" Then
                        If Not clsCommonFunction.IsAuthorised(sSecureAccessKey, PermissionType.RightAdd) Then
                            MsgBox(ReadResource("SecureAccess.FunctionNotAuthorised"), MsgBoxStyle.Exclamation, Application.ProductName)
                            Exit Sub
                        End If
                    End If
                    eActionMode = eNumActionMode.AddNew
                    drRow = ShowFormDetailTree()
                    If Not drRow Is Nothing Then
                        'gdsDictionary.Tables(sTableName).Rows.Add(row)
                        strKeyReturn = drRow.Item(sTablePrimaryKeyTree)
                        LoadDataTree()
                        treeList.ActiveNode = treeList.GetNodeByKey(strKeyReturn)
                        treeList.ActiveNode.Selected = True
                        'treeList.ActiveNode.Override.ActiveNodeAppearance.BackColor = Color.Red
                        treeList.ActiveNode.BringIntoView()
                    End If
                Case "mnuEditTree"    ' ButtonTool
                    'Check permision
                    If sSecureAccessKey <> "" Then
                        If Not clsCommonFunction.IsAuthorised(sSecureAccessKey, PermissionType.RightAdd) Then
                            MsgBox(ReadResource("SecureAccess.FunctionNotAuthorised"), MsgBoxStyle.Exclamation, Application.ProductName)
                            Exit Sub
                        End If
                    End If
                    If Not IsNothing(treeList.ActiveNode) Then
                        eActionMode = eNumActionMode.Edit
                        If Not CheckValidateTree() Then
                            Exit Sub
                        End If
                        drRow = ShowFormDetailTree()
                        If Not drRow Is Nothing Then
                            'gdsDictionary.Tables(sTableName).Rows.Add(row)
                            strKeyReturn = drRow.Item(sTablePrimaryKeyTree)
                            LoadDataTree()
                            treeList.ActiveNode = treeList.GetNodeByKey(strKeyReturn)
                            treeList.ActiveNode.Selected = True
                            'treeList.ActiveNode.Override.ActiveNodeAppearance.BackColor = Color.Red
                            treeList.ActiveNode.BringIntoView()
                        End If
                    End If
                Case "mnuDeleteTree"    ' ButtonTool
                    'Check permision
                    If sSecureAccessKey <> "" Then
                        If Not clsCommonFunction.IsAuthorised(sSecureAccessKey, PermissionType.RightAdd) Then
                            MsgBox(ReadResource("SecureAccess.FunctionNotAuthorised"), MsgBoxStyle.Exclamation, Application.ProductName)
                            Exit Sub
                        End If
                    End If
                    eActionMode = eNumActionMode.Delete
                    If Not CheckValidateTree() Then
                        Exit Sub
                    End If
                    DeleteTree()
                Case "mnuReload"  ' ButtonTool
                    ' Place code€u104 ?ere
                    LoadDataTree()

            End Select
        Catch ex As Exception
            MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub


    Private Sub treeList_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles treeList.KeyPress
        Try
            If e.Handled = False Then
                If e.KeyChar = Microsoft.VisualBasic.ChrW(13) Then
                    eActionMode = eNumActionMode.Edit
                    ShowFormDetailTree()
                End If
                If e.KeyChar = Microsoft.VisualBasic.ChrW(Keys.Delete) Then
                    eActionMode = eNumActionMode.Edit
                    If Not CheckValidateTree() Then
                        Exit Sub
                    End If
                    DeleteTree()
                End If
            End If

        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Exclamation, Application.ProductName)
        End Try
    End Sub
#End Region

#Region "Functions and Subs"

    Private Sub FilterObject()
        If Not oTreeKey Is Nothing Then
            ' Biến iIndex không cần thiết, Không sử dụng lệnh FilterConditions vì khi đó khó viết hàm Print
            ' Dim iIndex€u65 ?s Integer
            'Dim sCompareValue As String
            Dim vObjectList As New DataView(gdsDictionary.Tables(TableName))
            If oTreeKey.GetType.Name = "String" Then
                vObjectList.RowFilter = sTablePrimaryKeyTree + "=" + "'" + oTreeKey.ToString + "'"
            Else
                vObjectList.RowFilter = sTablePrimaryKeyTree + "=" + oTreeKey.ToString
            End If
            'sCompareValue = grdList.DisplayLayout.Bands(0).Columns("ObjectTypeID").ValueList.GetText(iObjectType, 0)
            grdList.DataSource = vObjectList
            'grdList.DisplayLayout.Bands(0).ColumnFilters("ObjectTypeID").FilterConditions.Add(Infragistics.Win.UltraWinGrid.FilterComparisionOperator.Equals, sCompareValue)
            'Me.Text = ReadResource("ObjectList.FormCaption") & " " & sCompareValue
        Else
            grdList.DataSource = gdsDictionary.Tables(TableName)
        End If
        grdList.DataBind()
    End Sub

    Private Function ShowFormDetailTree() As DataRow
        Select Case eActionMode
            Case eNumActionMode.AddNew
                If Not treeList.ActiveNode Is Nothing Then
                    If Not treeList.ActiveNode.Parent Is Nothing Then
                        oRowTree = gdsDictionary.Tables(sTable1NameTree).Rows.Find(treeList.ActiveNode.Parent.Cells(sTablePrimaryKeyTree).Value)
                    Else
                        oRowTree = gdsDictionary.Tables(sTable1NameTree).NewRow
                    End If
                Else
                    oRowTree = gdsDictionary.Tables(sTable1NameTree).NewRow
                End If
            Case eNumActionMode.Edit
                If treeList.ActiveNode Is Nothing Then
                    MsgBox("Chưa sửa đổi được")
                    Return Nothing
                Else
                    oRowTree = gdsDictionary.Tables(sTable1NameTree).Rows.Find(treeList.ActiveNode.Cells(sTablePrimaryKeyTree).Value)
                End If
        End Select
        Dim ofrm As Object
        ofrm = clsCommonFunction.GetFormByName(sFormDetailNameTree)
        If Not IsNothing(ofrm) Then
            ofrm.RowDetail = oRowTree
            ofrm.ActionMode = eActionMode
            If ofrm.ShowDialog() = Windows.Forms.DialogResult.OK Then
                Return ofrm.RowDetail
            Else
                Return Nothing
            End If
            ofrm.Dispose()
        End If
        'added for not warning
        Return oRowTree
    End Function

    Private Function CheckValidateTree() As Boolean
        Select Case eActionMode
            Case eNumActionMode.Edit
                If treeList.ActiveNode Is Nothing Then
                    Return False
                End If
                'If treeList.ActiveNode.Cells("IsSystem").Value = 1 Then
                '    MessageBox.Show(ReadResource("Dictionary.IsSystem"), Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                '    Return False
                'End If
            Case eNumActionMode.Delete
                If treeList.ActiveNode Is Nothing Then
                    Return False
                End If
                If treeList.SelectedNodes.Count = 1 Then
                    With treeList.SelectedNodes(0)
                        If .HasNodes Then
                            MessageBox.Show("Nhóm đã có nhóm con, vui lóng xóa nhóm con trước.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                            Return False
                        End If
                        If grdList.Rows.VisibleRowCount > 1 Then
                            MessageBox.Show("Nhóm đã có hàng hóa, vui lòng xóa mặt hàng trước.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                            Return False
                        End If
                        'If .Cells("IsSystem").Value = 1 Then
                        '    MessageBox.Show(ReadResource("Dictionary.IsSystem"), Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                        '    Return False
                        'End If
                    End With
                End If
        End Select
        Return True
    End Function

    'Public Overrides Sub ShowFormDetail()
    '    'Select Case eActionMode
    '    '    Case eNumActionMode.AddNew
    '    '        DictionaryRow = gdsDictionary.Tables(TableName).NewRow
    '    '    Case eNumActionMode.Edit
    '    '        DictionaryRow = gdsDictionary.Tables(TableName).Rows.Find(grdList.ActiveRow.Cells(TablePrimaryKey).Value)
    '    '    Case eNumActionMode.QuickAdd
    '    '        DictionaryRow = gdsDictionary.Tables(TableName).Rows.Find(grdList.ActiveRow.Cells(TablePrimaryKey).Value)
    '    'End Select
    '    'Dim ofrm As Object
    '    'ofrm = clsCommonFunction.GetFormByName(FormDetail)
    '    'If Not IsNothing(ofrm) Then
    '    '    If Not treeList.ActiveNode Is Nothing Then
    '    '        ofrm.ParentIDValue = treeList.ActiveNode.DataKey
    '    '    End If
    '    '    ofrm.RowCount = grdList.Rows.Count
    '    '    ofrm.RowDetail = DictionaryRow
    '    '    ofrm.ActionMode = eActionMode
    '    '    ofrm.ShowDialog()
    '    '    ofrm.Dispose()
    '    '    GetRowCount()
    '    'End If
    'End Sub
#End Region


    Private Sub treeList_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles treeList.MouseDown
        If e.Button = Windows.Forms.MouseButtons.Right Then
            Dim NodeAtPoint As Infragistics.Win.UltraWinTree.UltraTreeNode
            NodeAtPoint = treeList.GetNodeFromPoint(e.X, e.Y)
            If Not NodeAtPoint Is Nothing Then
                NodeAtPoint.Selected = True
                oTreeKey = NodeAtPoint.Key
                FilterObject()
                'GetRowCount()
            End If
        End If

    End Sub

End Class
